package com.kgcx.order.service;

import com.github.pagehelper.PageHelper;
import com.kgcx.common.bean.RequestData;
import com.kgcx.common.client.organization.pojo.CustomerMsg;
import com.kgcx.common.eum.CommonDataEeum;
import com.kgcx.common.eum.OrderEnum;
import com.kgcx.common.rabbitmq.producer.CustomerMsgProducer;
import com.kgcx.common.redis.JsonRedisTemplate;
import com.kgcx.common.utils.MoneyUtil;
import com.kgcx.common.utils.UUIDUtils;
import com.kgcx.dbutils.service.DictService;
import com.kgcx.dbutils.utils.PageUtils;
import com.kgcx.order.domain.Order;
import com.kgcx.order.domain.PayRecord;
import com.kgcx.order.domain.PayRecordDomain;
import com.kgcx.order.mapper.PayRecordMapper;
import com.kgcx.order.rabbitmq.PayProducer;
import com.kgcx.pay.util.AliPayUtil;
import com.kgcx.pay.util.PayCallbackBean;
import com.kgcx.pay.util.PayPreInfoBean;
import com.kgcx.pay.util.WeChatUtil;
import com.xiaoleilu.hutool.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 支付相关服务
 *
 * @author qinze
 */
@Slf4j
@Service
public class PayService {

    @Resource
    private AliPayUtil aliPayUtil;
    @Resource
    private WeChatUtil weChatUtil;
    @Resource
    private PayRecordMapper payRecordMapper;
    @Resource
    private OrderService orderService;
    @Resource
    private JsonRedisTemplate<Long> jsonRedisTemplate;
    // @Autowired
    // private StringRedisTemplate strRedisTemplate;
    @Resource
    private PayProducer payProducer;
    @Resource
    private CustomerMsgProducer customerMsgProducer;

    @Resource
    private DictService dictService;

    private final static String ALIPAY_LOCK_KEY = "alipay:lock:key";

    private final static String WECHAT_LOCK_KEY = "wechat:lock:key";

    private final static String title = "支付提醒";
    private final static String content = "您%s%s用车，行程总费用为%s元，现已支付成功。欢迎再次使用空港专车。";

    @Value("${aliPay.callback.url}")
    private String alipayUrl;

    @Value("${weChatPay.callback.url}")
    private String weChatUrl;

    /**
     * 创建支付宝预支付订单
     *
     * @param payRecord
     * @param payClientType 支付端类型
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public PayPreInfoBean addAlipayPayInfo(PayRecord payRecord, int payClientType) {
        PayPreInfoBean payPreInfoBean = new PayPreInfoBean();
        if (StringUtils.isBlank(payRecord.getOrderNo())) {
            payPreInfoBean.setPayStatus(false);
            payPreInfoBean.setPayInfo("订单号不能为空");
            return payPreInfoBean;
        }
        if (null == payRecord.getCreateId() || payRecord.getCreateId() <= 0) {
            payPreInfoBean.setPayStatus(false);
            payPreInfoBean.setPayInfo("用户ID错误");
            return payPreInfoBean;
        }
        Order order = null;
        if (CommonDataEeum.PAY_TYEP_SMALL_ROUTINE.getCode() == payClientType
                || CommonDataEeum.PAY_TYEP_PASSENGER.getCode() == payClientType) {
            payRecord.setPayType(OrderEnum.PAY_TYPE_USER);
            // 订单查询
            order = orderService.getIngOrderByOrderNo(payRecord.getOrderNo());
            if (null == order) {
                payPreInfoBean.setPayStatus(false);
                payPreInfoBean.setPayInfo("订单不存在");
                return payPreInfoBean;
            }
            if (OrderEnum.USER_PAYING != order.getOrderState()) {
                payPreInfoBean.setPayStatus(false);
                payPreInfoBean.setPayInfo("订单还在进行或已结束");
                return payPreInfoBean;
            }
        } else if (CommonDataEeum.PAY_TYEP_DRIVER.getCode() == payClientType) {
            payRecord.setPayType(OrderEnum.PAY_TYPE_DRIVER);
            order = orderService.getByOrderNo(payRecord.getOrderNo());
            if (null == order) {
                payPreInfoBean.setPayStatus(false);
                payPreInfoBean.setPayInfo("订单不存在");
                return payPreInfoBean;
            }
            if (OrderEnum.MARKED_PAIED != order.getOrderState()) {
                payPreInfoBean.setPayStatus(false);
                payPreInfoBean.setPayInfo("订单还在进行或已结束");
                return payPreInfoBean;
            }
        }
        if (null == order.getFactFinalPrice()) {
            payPreInfoBean.setPayStatus(false);
            payPreInfoBean.setPayInfo("factFinalPrice金额错误");
            return payPreInfoBean;
        }
        if (null == order.getFactPrice()) {
            payPreInfoBean.setPayStatus(false);
            payPreInfoBean.setPayInfo("factPrice金额错误");
            return payPreInfoBean;
        }
        payRecord.setFactPrice(Long.parseLong(order.getFactFinalPrice().toString()));// 实际结算金额
        payRecord.setPrice(Long.parseLong(order.getFactPrice().toString()));// 总金额 未使用优惠卷
        if (null != order.getCouponId() && order.getCouponId() > 0) {
            payRecord.setCouponId(Long.parseLong(order.getCouponId().toString()));// 优惠卷ID
            int i = order.getFactPrice() - order.getFactFinalPrice();
            payRecord.setBenfitPrice(Long.parseLong(i + ""));
        }
        // 如果支付金额为0 则直接支付完成
        if (0L == payRecord.getFactPrice().longValue()) {
            payPreInfoBean.setPayStatus(false);
            payPreInfoBean.setPayInfo("PRICE_SUCCESS");
            order.setOrderState(OrderEnum.PAIED);
            order.setPaiedTime(new Timestamp(System.currentTimeMillis()));
            if (CommonDataEeum.PAY_TYEP_SMALL_ROUTINE.getCode() == payClientType
                    || CommonDataEeum.PAY_TYEP_PASSENGER.getCode() == payClientType) {
                if (null != order) {
                    setOperatePay(payRecord, order);
                    orderService.paiedPersistence(order);
                }
            } else if (CommonDataEeum.PAY_TYEP_DRIVER.getCode() == payClientType) {
                if (null != order) {
                    setOperatePay(payRecord, order);
                    orderService.driverPayUpdate(order);
                }
            }
            return payPreInfoBean;
        }
        String payOrderNo = RandomUtil.randomUUID().replaceAll("-", "");
        String factPriceStr = MoneyUtil.getMoney(payRecord.getFactPrice()); // 支付宝支付金额单位为元 金额需要做计算
        payPreInfoBean = aliPayUtil.alipayPayInfo(payRecord.getOrderNo(), factPriceStr, alipayUrl, payOrderNo, payClientType);
        if (!payPreInfoBean.getPayStatus()) {
            payPreInfoBean.setPayInfo("预支付迷路了，请稍后重试");
            return payPreInfoBean;
        }
        payRecord.setLinePrice(payRecord.getFactPrice());
        payRecord.setPayOrderNo(payOrderNo);
        payRecord.setStatus(CommonDataEeum.DATA_STATE_NORMAL.getCode());
        payRecord.setPayState(CommonDataEeum.PAY_STATE_NO_RECKON.getCode());
        // 创建用户支付订单 状态未完成
        payRecordMapper.insertPayRecord(payRecord);
        return payPreInfoBean;
    }

    /**
     * 支付宝支付回调
     *
     * @param valideData
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String alipayCallback(Map<String, String> valideData) {
        log.info(String.format("支付宝回调：valideData= %s。", valideData));
        ValueOperations<String, Long> vOp = jsonRedisTemplate.opsForValue();
        String payOrderId = valideData.get("out_trade_no");// 不是打车的订单号，是支付系统生成的订单号
        if (StringUtils.isBlank(payOrderId)) {
            log.info(String.format("out_trade_no参数未获取到,out_trade_no= %s。", valideData.get("out_trade_no")));
            return "fail";
        }
        // 锁1秒
        if (vOp.setIfAbsent(ALIPAY_LOCK_KEY + payOrderId, 0L)) {
            vOp.getOperations().expire(ALIPAY_LOCK_KEY + payOrderId, 1, TimeUnit.SECONDS);
            log.info("阿里支付回掉valideData={}", valideData);
            // 获取订单
            PayRecord payRecord = payRecordMapper.getPayInfoByPayOrderNo(payOrderId);
            if (null == payRecord) {
                log.info(String.format("orderId参数未能取到订单数据,payRecord= %s。", payRecord));
                return "fail";
            }
            if (CommonDataEeum.PAY_STATE_YES_RECKON.getCode() == payRecord.getPayState()) {// 1️已支付
                log.info(String.format("orderId已消费,状态= %s。", payRecord.getPayState()));
                return "success";
            }
            BigDecimal money = new BigDecimal(payRecord.getFactPrice());
            PayCallbackBean payCallbackBean = aliPayUtil.alipayCallback(valideData, money, payRecord.getPayType());
            log.info("支付宝回掉payStatus={}, CallBackInfo={}", payCallbackBean.getPayStatus(),
                    payCallbackBean.getPayCallBackInfo());
            if (!payCallbackBean.getPayStatus()) {
                return "fail";
            }
            try {
                log.info(String.format("alipay回调.begin，订单号= %s。", payRecord.getOrderNo()));
                String orderNo = payRecord.getOrderNo();
                // 修改订单状态
                payRecordMapper.updatePayInfoState(payOrderId, CommonDataEeum.PAY_STATE_YES_RECKON.getCode(),
                        payRecord.getCreateId(), new Timestamp(System.currentTimeMillis()),
                        new Timestamp(System.currentTimeMillis()));
                Order order = null;
                if (OrderEnum.PAY_TYPE_USER == payRecord.getPayType()) {
                    log.info(String.format("alipay回调.乘客支付，订单号= %s。", payRecord.getOrderNo()));
                    order = orderService.getIngOrderByOrderNo(orderNo);
                    if (null != order) {
                        setOperatePay(payRecord, order);
                        order.setOrderState(OrderEnum.PAIED);
                        //1-微信，2-支付宝，3-银联，4-账户扣款，5-企业代扣，9-其他
                        order.setPayChannel(OrderEnum.APY_CHANNEL_ALIPAY);
                        order.setPaiedTime(new Timestamp(System.currentTimeMillis()));
                        orderService.paiedPersistence(order);
                    }
                } else if (OrderEnum.PAY_TYPE_DRIVER == payRecord.getPayType()) {
                    log.info(String.format("alipay回调.司机代付，订单号= %s。", payRecord.getOrderNo()));
                    order = orderService.getByOrderNo(orderNo);
                    if (null != order) {
                        setOperatePay(payRecord, order);
                        order.setOrderState(OrderEnum.PAIED);
                        order.setPaiedTime(new Timestamp(System.currentTimeMillis()));
                        //1-微信，2-支付宝，3-银联，4-账户扣款，5-企业代扣，9-其他
                        order.setPayChannel(OrderEnum.APY_CHANNEL_ALIPAY);
                        orderService.driverPayUpdate(order);
                    }
                }
                sendAppPayMessage(payRecord.getCreateId(), order.getPlanDepartTime(), payRecord.getFactPrice(), order.getOrderType());

            } catch (Exception e) {
                // 数据操作失败
                payCallbackBean.setPayCallBackInfo("服务器信息：支付回调失败，操作自动稍后重试");
                payCallbackBean.setPayStatus(false);
                log.error(String.format("入库操作失败orderNo= %s。", payRecord.getOrderNo()), e);
                return "fail";
            }
        }
        return "success";
    }

    /**
     * 微信预支付
     *
     * @param payRecord
     * @param payClientType 支付端类型
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public PayPreInfoBean addWeChatPayInfo(PayRecord payRecord, int payClientType) {
        PayPreInfoBean payPreInfoBean = new PayPreInfoBean();
        if (StringUtils.isBlank(payRecord.getOrderNo())) {
            payPreInfoBean.setPayStatus(false);
            payPreInfoBean.setPayInfo("订单号不能为空");
            return payPreInfoBean;
        }
        if (null == payRecord.getCreateId() || payRecord.getCreateId() <= 0) {
            payPreInfoBean.setPayStatus(false);
            payPreInfoBean.setPayInfo("用户ID错误");
            return payPreInfoBean;
        }
        Order order = null;
        if (CommonDataEeum.PAY_TYEP_SMALL_ROUTINE.getCode() == payClientType
                || CommonDataEeum.PAY_TYEP_PASSENGER.getCode() == payClientType) {
            payRecord.setPayType(OrderEnum.PAY_TYPE_USER);
            order = orderService.getIngOrderByOrderNo(payRecord.getOrderNo());
            if (null == order) {
                payPreInfoBean.setPayStatus(false);
                payPreInfoBean.setPayInfo("订单不存在");
                return payPreInfoBean;
            }
            if (OrderEnum.USER_PAYING != order.getOrderState()) {
                payPreInfoBean.setPayStatus(false);
                payPreInfoBean.setPayInfo("订单还在进行或已结束");
                return payPreInfoBean;
            }
        } else if (CommonDataEeum.PAY_TYEP_DRIVER.getCode() == payClientType) {
            payRecord.setPayType(OrderEnum.PAY_TYPE_DRIVER);
            order = orderService.getByOrderNo(payRecord.getOrderNo());
            if (null == order) {
                payPreInfoBean.setPayStatus(false);
                payPreInfoBean.setPayInfo("订单不存在");
                return payPreInfoBean;
            }
            if (OrderEnum.MARKED_PAIED != order.getOrderState()) {
                payPreInfoBean.setPayStatus(false);
                payPreInfoBean.setPayInfo("订单还在进行或已结束");
                return payPreInfoBean;
            }
        }
        if (null == order.getFactFinalPrice()) {
            payPreInfoBean.setPayStatus(false);
            payPreInfoBean.setPayInfo("factFinalPrice金额错误");
            return payPreInfoBean;
        }
        if (null == order.getFactPrice()) {
            payPreInfoBean.setPayStatus(false);
            payPreInfoBean.setPayInfo("factPrice金额错误");
            return payPreInfoBean;
        }
        payRecord.setFactPrice(Long.parseLong(order.getFactFinalPrice().toString()));// 实际结算金额
        payRecord.setPrice(Long.parseLong(order.getFactPrice().toString()));// 总金额 未使用优惠卷
        if (null != order.getCouponId() && order.getCouponId() > 0) {
            payRecord.setCouponId(Long.parseLong(order.getCouponId().toString()));// 优惠卷ID
            int i = order.getFactPrice() - order.getFactFinalPrice();
            payRecord.setBenfitPrice(Long.parseLong(i + ""));
        }
        // 如果支付金额为0 则直接支付完成
        if (0L == payRecord.getFactPrice().longValue()) {
            payPreInfoBean.setPayStatus(false);
            payPreInfoBean.setPayInfo("PRICE_SUCCESS");
            order.setOrderState(OrderEnum.PAIED);
            order.setPaiedTime(new Timestamp(System.currentTimeMillis()));
            if (CommonDataEeum.PAY_TYEP_SMALL_ROUTINE.getCode() == payClientType
                    || CommonDataEeum.PAY_TYEP_PASSENGER.getCode() == payClientType) {
                if (null != order) {
                    setOperatePay(payRecord, order);
                    orderService.paiedPersistence(order);
                }
            } else if (CommonDataEeum.PAY_TYEP_DRIVER.getCode() == payClientType) {
                if (null != order) {
                    setOperatePay(payRecord, order);
                    orderService.driverPayUpdate(order);
                }
            }
            return payPreInfoBean;
        }
        String payOrderNo = RandomUtil.randomUUID().replaceAll("-", "");
        // 微信交易金额单位为分
        payPreInfoBean = weChatUtil.getWeChatPayInfo(payRecord.getOrderNo(), String.valueOf(payRecord.getFactPrice()),
                payRecord.getIp(), weChatUrl, payClientType, payRecord.getOpenId(), payOrderNo);
        if (!payPreInfoBean.getPayStatus()) {
            return payPreInfoBean;
        }
        payRecord.setLinePrice(payRecord.getFactPrice());
        payRecord.setPayOrderNo(payOrderNo);
        payRecord.setStatus(CommonDataEeum.DATA_STATE_NORMAL.getCode());
        payRecord.setPayState(CommonDataEeum.PAY_STATE_NO_RECKON.getCode());
        // 创建用户支付订单 状态未完成
        payRecordMapper.insertPayRecord(payRecord);
        return payPreInfoBean;
    }

    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> weChatCallback(Map<String, String> valideData) {
        log.info(String.format("微信回调：valideData= %s。", valideData));
        Map<String, String> returnMap = new HashMap<String, String>();
        ValueOperations<String, Long> vOp = jsonRedisTemplate.opsForValue();
        PayCallbackBean payCallbackBean = weChatUtil.parserPayCallback(valideData);
        if (!payCallbackBean.getPayStatus()) {
            returnMap.put("return_code", "FAIL");
            returnMap.put("return_msg", payCallbackBean.getPayCallBackInfo());
            return returnMap;
        }
        String payOrderId = payCallbackBean.getOrderSn();// 此订单号是支付订单号
        // 锁1秒
        if (vOp.setIfAbsent(WECHAT_LOCK_KEY + payOrderId, 0L)) {
            vOp.getOperations().expire(WECHAT_LOCK_KEY + payOrderId, 1, TimeUnit.SECONDS);
            // 获取订单
            PayRecord payRecord = payRecordMapper.getPayInfoByPayOrderNo(payOrderId);
            if (null == payRecord) {
                log.info(String.format("orderId参数未能取到订单数据,payRecord= %s。", payRecord));
                // 不需要做重试
                returnMap.put("return_code", "FAIL");
                returnMap.put("return_msg", "订单不存在");
                return returnMap;
            }
            if (CommonDataEeum.PAY_STATE_YES_RECKON.getCode() == payRecord.getPayState()) {// 1️已支付
                log.info(String.format("orderId已消费,状态= %s。", payRecord.getPayState()));
                returnMap.put("return_code", "SUCCESS");
                returnMap.put("return_msg", "OK");
                return returnMap;
            }
            BigDecimal money = new BigDecimal(payRecord.getFactPrice());// 内部系统订单的金额
            Long payAmount = Long.parseLong(payCallbackBean.getPayAmount());// 第三方的金额
            BigDecimal callbackMoney = new BigDecimal(payAmount);
            if (money.compareTo(callbackMoney) != 0) { // 总金额，以分为单位
                returnMap.put("return_code", "FAIL");
                returnMap.put("return_msg", "金额不正确");
                return returnMap;
            }
            try {
                String orederId = payRecord.getOrderNo();
                // 修改订单状态
                payRecordMapper.updatePayInfoState(payOrderId, CommonDataEeum.PAY_STATE_YES_RECKON.getCode(),
                        payRecord.getCreateId(), new Timestamp(System.currentTimeMillis()),
                        new Timestamp(System.currentTimeMillis()));
                Order order = null;
                if (OrderEnum.PAY_TYPE_USER == payRecord.getPayType()) {
                    order = orderService.getIngOrderByOrderNo(orederId);
                    if (null != order) {
                        setOperatePay(payRecord, order);
                        //1-微信，2-支付宝，3-银联，4-账户扣款，5-企业代扣，9-其他
                        order.setPayChannel(OrderEnum.APY_CHANNEL_WECHATPAY);
                        order.setOrderState(OrderEnum.PAIED);
                        order.setPaiedTime(new Timestamp(System.currentTimeMillis()));
                        orderService.paiedPersistence(order);
                    }
                } else if (OrderEnum.PAY_TYPE_DRIVER == payRecord.getPayType()) {
                    order = orderService.getByOrderNo(orederId);
                    if (null != order) {
                        order.setOrderState(OrderEnum.PAIED);
                        order.setPaiedTime(new Timestamp(System.currentTimeMillis()));
                        setOperatePay(payRecord, order);
                        //1-微信，2-支付宝，3-银联，4-账户扣款，5-企业代扣，9-其他
                        order.setPayChannel(OrderEnum.APY_CHANNEL_WECHATPAY);
                        orderService.driverPayUpdate(order);
                    }
                }

                sendAppPayMessage(payRecord.getCreateId(), order.getPlanDepartTime(), payRecord.getFactPrice(), order.getOrderType());

            } catch (Exception e) {
                log.error(e.getMessage());
                // 数据操作失败
                returnMap.put("return_code", "FAIL");
                returnMap.put("return_msg", "支付失败");
                return returnMap;
            }
        }
        returnMap.put("return_code", "SUCCESS");
        returnMap.put("return_msg", "OK");
        return returnMap;
    }

    /**
     * 发送app支付完成消息
     *
     * @param customerId 乘客/司机id
     * @param date       用车时间
     * @param factPrice  金额
     * @param orderType  用车类型
     */
    public void sendAppPayMessage(Long customerId, Timestamp date, Long factPrice, Integer orderType) {
        Boolean isBook = false;//默认为立即用车
        if (OrderEnum.TYPE_PLAN_PLANE_PICK == orderType
                || OrderEnum.TYPE_PLAN_TRAIN_PICK == orderType
                || OrderEnum.TYPE_PLAN_PLANE_SEND == orderType
                || OrderEnum.TYPE_PLAN_TRAIN_SEND == orderType
                || OrderEnum.TYPE_PLAN_COMMON == orderType) {
            isBook = true;
        }
        String planDepartTime = DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss");
        String factPriceStr = MoneyUtil.getMoney(factPrice); //金额单位为元
        CustomerMsg customerMsg = new CustomerMsg();
        customerMsg.setCustomerId(customerId);
        customerMsg.setTypeId(1);
        customerMsg.setIsRead(CustomerMsg.UNREAD);
        customerMsg.setTitle(title);
        String c = "";
        if (isBook) {
            c = "预约";
        }
        String contentStr = String.format(content, c, planDepartTime, factPriceStr);
        customerMsg.setContent(contentStr);
        customerMsgProducer.customerMsgSend(customerMsg);
    }

    /**
     * 设置监管数据
     *
     * @param payRecord
     * @param order
     */
    private void setOperatePay(PayRecord payRecord, Order order) {
        PayRecordDomain payRecordDomain = new PayRecordDomain();
        BeanUtils.copyProperties(payRecord, payRecordDomain);
        if (null != order) {
            payRecordDomain.setOnArea(order.getPlanOrigCityId() == null ? 0 : order.getPlanOrigCityId());
            payRecordDomain.setDriverName(order.getDriverName() == null ? "" : order.getDriverName());
            payRecordDomain.setLicenseId(payRecord.getLicenseId() == null ? "" : payRecord.getLicenseId());
            payRecordDomain.setFareType(order.getFareType() == null ? 0 : order.getFareType());
            payRecordDomain.setVehicleNo(order.getAutoNo() == null ? "" : order.getAutoNo());
            payRecordDomain.setWaitTime(order.getWaitTime() == null ? 0 : order.getWaitTime());
            payRecordDomain.setBookDepTime(order.getPlanDepartTime() == null ? new Timestamp(System.currentTimeMillis()) : order.getPlanDepartTime());
            payRecordDomain.setDepLongItude(order.getActualOrigLng() == null ? "" : order.getActualOrigLng());
            payRecordDomain.setDepLatituDe(order.getActualOrigLat() == null ? "" : order.getActualOrigLat());
            payRecordDomain.setDepArea(order.getActualOrig() == null ? "" : order.getActualOrig());
            payRecordDomain.setDepTime(order.getDepTime() == null ? new Timestamp(System.currentTimeMillis()) : order.getDepTime());
            payRecordDomain.setDestLongitude(order.getActualDestLng() == null ? "" : order.getActualDestLng());
            payRecordDomain.setDestLatitude(order.getActualDestLat() == null ? "" : order.getActualDestLat());
            payRecordDomain.setDestArea(order.getPlanDest() == null ? "" : order.getPlanDest());
            payRecordDomain.setDestArea(order.getActualDest() == null ? "" : order.getActualDest());
            payRecordDomain.setDestTime(order.getDestTime() == null ? new Timestamp(System.currentTimeMillis()) : order.getDestTime());

            //String bookModelName = getModelName(order.getBookModel());
            payRecordDomain.setBookModel(order.getBookModel() == null ? 0 : order.getBookModel());
            //payRecordDomain.setBookModelName(bookModelName);

            payRecordDomain.setMode(order.getModel() == null ? 0 : order.getModel());
            //String modelName = order.getModel() == null ? getModelName(order.getBookModel()) : getModelName(order.getModel());
            //payRecordDomain.setModeName(modelName);

            payRecordDomain.setDriveMile(order.getDriveMile() == null ? 0 : order.getDriveMile());// m 监管km
            payRecordDomain.setDriveTime(order.getDriveTime() == null ? 0 : order.getDriveTime());
            payRecordDomain.setWaitMile(order.getWaitMile() == null ? 0 : order.getWaitMile());// m 监管km
            payRecordDomain.setFarUpPrice(0L);
            payRecordDomain.setOtherUpPrice(0L);
            payRecordDomain.setPayState(CommonDataEeum.PAY_STATE_YES_RECKON.getCode());// 已结算
            payRecordDomain.setPayTime(new Timestamp(System.currentTimeMillis()));
            payRecordDomain.setOrderMatchTime(new Timestamp(System.currentTimeMillis()));

            payRecordDomain.setAutoId(order.getAutoId());
            payRecordDomain.setDriverId(order.getDriverId());
            payRecordDomain.setCustomerId(order.getPlacingUserId());
            payRecordDomain.setPayType(payRecord.getPayType());

            if (order.getPayType() == 1) {
                payRecordDomain.setPayAccount(order.getPlacingUserPhone());
            } else {
                payRecordDomain.setPayAccount(order.getDriverPhone());
            }

            payProducer.addPayProducer(dictService.buildDictValue(payRecordDomain));
        }
    }


    /**
     * 通过查询给监管平台提供支付信息数据
     *
     * @param rd
     * @return
     */
    public List<PayRecord> queryPayRecordWithPage(RequestData rd) {
        PageUtils.page(rd);
        PageHelper.orderBy(rd.getOrderBy());
        List<PayRecord> list = payRecordMapper.queryPayInfoForList(rd);
        for (PayRecord prd : list) {
            Order order = orderService.getByOrderNo(prd.getOrderNo());// 获取数据库订单信息
            this.setOperatePay(prd, order);
        }
        return list;
    }

    /**
     * 根据时间统计营业额
     *
     * @param rd
     * @return
     */
    public Long queryTotalAmount(RequestData rd) {
        return payRecordMapper.queryTotalAmount(rd);
    }
}
